package com.snail.clouds.api.interceptor;

import com.snail.clouds.framework.service.AuthService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT认证拦截器
 */
@Slf4j
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {
    
    @Autowired
    private AuthService authService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            log.debug("处理OPTIONS预检请求");
            return true;
        }
        
        // 获取请求路径
        String requestURI = request.getRequestURI();
        log.debug("处理请求，URI: {}", requestURI);
        
        // 登录接口、验证Token接口不需要验证Token
        if (requestURI.contains("/api/auth/login") || 
            requestURI.contains("/api/auth/validate") ||
            requestURI.contains("/api/auth/refresh") ||
            requestURI.contains("/api/health") ||
            requestURI.matches("/api/common/.*")) {
            log.debug("无需认证的公开接口: {}", requestURI);
            return true;
        }
        
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        log.debug("Authorization头: {}", authHeader);
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.warn("未提供有效的Authorization头: {}", requestURI);
            sendErrorResponse(response, 401, "未提供有效的认证信息");
            return false;
        }
        
        // 提取Token
        String token = authHeader.substring(7);
        log.debug("提取的Token: {}", token);
        
        try {
            // 验证Token
            if (!authService.validateToken(token)) {
                log.warn("无效的Token: {}", requestURI);
                sendErrorResponse(response, 401, "Token无效或已过期");
                return false;
            }
            
            // 将用户ID和用户名放入请求属性中，供后续使用
            Long userId = authService.getUserIdFromToken(token);
            String username = authService.getUsernameFromToken(token);
            
            log.debug("Token验证通过，用户ID: {}, 用户名: {}", userId, username);
            
            request.setAttribute("userId", userId);
            request.setAttribute("username", username);
            
            return true;
        } catch (Exception e) {
            log.error("Token验证异常: {}", e.getMessage(), e);
            sendErrorResponse(response, 401, "Token验证失败");
            return false;
        }
    }
    
    /**
     * 发送错误响应
     * @param response HTTP响应
     * @param status 状态码
     * @param message 错误消息
     * @throws IOException IO异常
     */
    private void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        log.warn("发送错误响应，状态码: {}, 消息: {}", status, message);
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("code", status);
        errorResponse.put("message", message);
        errorResponse.put("data", null);
        errorResponse.put("timestamp", System.currentTimeMillis());
        
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
    }
}